// @ts-nocheck
const { Controller } = require('egg');
const iconv = require('iconv-lite');
const fs = require('fs');
const { v4: uuidv4 } = require("uuid");
const dayjs = require('dayjs');
const { transcation_classification_enum } = require('../public/js/index');

class BillController extends Controller {
  async getBillAll() {
    const { ctx } = this;
    let { endTime } = ctx.request.body;
    if (endTime) {
      endTime = dayjs(endTime).add(1, 'day').format('YYYY-MM-DD');
      delete ctx.request.body.endTime;
    }
    const data = await ctx.service.bill.findAll({ ...ctx.request.body, endTime });
    const sum = await ctx.service.bill.querySum({ ...ctx.request.body, endTime });
    ctx.body = {
      code: this.config.code.SUCCESS,
      data: {
        data,
        sum
      },
      msg: '获取成功'
    };
  }
  async getBillAllByDay() {
    const { ctx } = this;
    let { startTime, endTime, month } = ctx.request.body;
    month = month || dayjs().format('YYYY-MM');
    console.log(month);
    delete ctx.request.body.month;
    let data = await ctx.service.bill.getBillAllByDay({ ...ctx.request.body, month });
    console.log(data);
    if (data.length) {
      data = data.map(item => {
        if (item.children) {
          item.children = JSON.parse(`[${item.children}]`);
        }
        return item;
      })
    }
    if (!(startTime && endTime)) {
      startTime = `${month}-1`;
      endTime = dayjs(month).add(1, 'month').format('YYYY-MM-DD');
    }
    console.log(startTime);
    console.log(endTime);
    const sum = await ctx.service.bill.querySum({ ...ctx.request.body, startTime, endTime });
    ctx.body = {
      code: this.config.code.SUCCESS,
      data: {
        data,
        sum
      },
      msg: '获取成功'
    };
  }
  async getBillStatistics() {
    const { ctx } = this;
    let { startTime, endTime, type } = ctx.request.body;
    if (startTime && endTime && type) {
      try {
        const trend = await ctx.service.bill.getExpenditureTrend({ startTime, endTime, type });
        const classification = await ctx.service.bill.getClassificationOfExpenditure({ startTime, endTime, type });
        const rank = await ctx.service.bill.getExpenditureRank({ startTime, endTime, type });
        const sumMoney = await ctx.service.bill.getSumMoneyByType({ startTime, endTime, type });
        const expendSumMoney = await ctx.service.bill.getExpendSumMoney({ startTime, endTime });
        const budget = await ctx.service.user.getBudget();
        ctx.body = {
          code: this.config.code.SUCCESS,
          data: {
            trend,
            classification,
            rank,
            sumMoney: sumMoney.sumMoney || 0,
            budget: budget.budget || 0,
            expendSumMoney: expendSumMoney.expendSumMoney || 0,
          },
          msg: '获取成功'
        };
      } catch (err) {
        ctx.throw(this.app.config.code.ERROR, err);
      }

    } else {
      ctx.body = {
        code: this.config.code.ERROR,
        data: null,
        msg: '获取失败，未传必传参数startTime、endTime、payType'
      };
    }
  }
  async insertZFBData() {
    try {
      const { ctx } = this;
      const file = ctx.request.files[0];
      let billArr = []
      const buffer = fs.readFileSync(file.filepath);
      // 使用iconv-lite将Buffer对象从GB2312转换为UTF-8字符串
      let data = iconv.decode(buffer, 'gb2312');
      const arr = data.split("\n");
      const newArr = arr.slice(25, (arr.length - 1));
      // console.log(transcation_classification_enum);
      newArr.forEach(item => {
        const itemArr = item.split(',');
        let type;
        if (itemArr[5] === '支出') {
          type = 2
        } else if (itemArr[5] === '收入') {
          type = 1
        } else {
          type = 3
        }
        billArr.push({
          id: uuidv4(),
          payTime: itemArr[0],
          transactionType: getTranscationClassificationVal(itemArr[1]),
          trader: itemArr[2],
          tradingAccount: itemArr[3],
          notes: itemArr[4],
          type,
          money: +itemArr[6],
          paymentMethod: itemArr[7],
          transactionOrderNumber: itemArr[9],
          merchantOrderNumber: itemArr[10],
          userId: '66884818-6d20-4aab-8529-6e6c2042083b',
          payType: 1,
          isDelete: 2
        })
        // billArr.push([uuidv4(), itemArr[0], getTranscationClassificationVal(itemArr[1]), itemArr[2], itemArr[3], itemArr[4], itemArr[5] === '支出' ? 2 : 1, +itemArr[6], itemArr[7], itemArr[9], itemArr[10], '66884818-6d20-4aab-8529-6e6c2042083b'])
      })
      // console.log(billArr.length);
      const result = ctx.service.bill.insert(billArr);
      ctx.body = {
        code: this.config.code.SUCCESS,
        data: result,
        msg: '插入成功'
      }
      // ctx.body = billArr;
    } catch (err) {
      this.ctx.throw(this.app.config.code.ERROR, err);
    }
  }
  async insertWXData() {
    try {
      const { ctx } = this;
      const file = ctx.request.files[0];
      let billArr = []
      const buffer = fs.readFileSync(file.filepath);
      const data = iconv.decode(buffer, 'utf-8');
      const arr = data.split("\n");
      const newArr = arr.slice(17, (arr.length - 1))
      // console.log(transcation_classification_enum);
      newArr.forEach(item => {
        const itemArr = item.split(',');
        let type;
        if (itemArr[4] === '支出') {
          type = 2
        } else if (itemArr[4] === '收入') {
          type = 1
        } else {
          type = 3
        }
        billArr.push({
          id: uuidv4(),
          payTime: itemArr[0],
          transactionType: getTranscationClassificationVal(itemArr[1]),
          trader: itemArr[2],
          notes: itemArr[3],
          type,
          money: +itemArr[5].slice(1),
          paymentMethod: itemArr[6],
          transactionOrderNumber: itemArr[8],
          merchantOrderNumber: itemArr[9],
          userId: '66884818-6d20-4aab-8529-6e6c2042083b',
          payType: 2,
          isDelete: 2
        })
        // billArr.push([uuidv4(), itemArr[0], getTranscationClassificationVal(itemArr[1]), itemArr[2], itemArr[3], itemArr[4], itemArr[5] === '支出' ? 2 : 1, +itemArr[6], itemArr[7], itemArr[9], itemArr[10], '66884818-6d20-4aab-8529-6e6c2042083b'])
      })
      const result = ctx.service.bill.insert(billArr);
      ctx.body = {
        code: this.config.code.SUCCESS,
        data: result,
        msg: '插入成功'
      }
      // ctx.body = billArr;
    } catch (err) {
      this.ctx.throw(this.app.config.code.ERROR, err);
    }
  }
  async deleteBill() {
    const { ctx } = this;
    let { endTime } = ctx.request.body;
    if (endTime) {
      endTime = dayjs(endTime).add(1, 'day').format('YYYY-MM-DD');
      delete ctx.request.body.endTime;
    }
    const data = await ctx.service.bill.delete({ ...ctx.request.body, endTime });
    ctx.body = {
      code: this.config.code.SUCCESS,
      data,
      msg: '删除成功'
    };
  }
  async getDataByTransactionType() {
    const { ctx } = this;
    console.log(ctx.request.body);
    let { startTime, endTime, type, transactionType } = ctx.request.body;
    if (startTime && endTime && type && transactionType) {
      try {
        const data = await ctx.service.bill.getDataByTransactionType({ startTime, endTime, type, transactionType });
        const sum = await ctx.service.bill.getSumDataByTransactionType({ startTime, endTime, type, transactionType });
        console.log(sum);
        ctx.body = {
          code: this.config.code.SUCCESS,
          data: {
            data,
            sum: sum.sum
          },
          msg: '获取成功'
        };
      } catch (err) {
        ctx.throw(this.app.config.code.ERROR, err);
      }

    } else {
      ctx.body = {
        code: this.config.code.ERROR,
        data: null,
        msg: '获取失败，未传必传参数startTime、endTime、type、transactionType'
      };
    }
  }
}

const getTranscationClassificationVal = (name) => {
  // console.log(name);
  // 微信支付账单(20221101-20230131)
  if (name.indexOf('退款') !== -1) {
    return 28;
  }
  if (name.indexOf('微信红包') !== -1) {
    return 37;
  }
  if (!transcation_classification_enum.some(item => item.value === name)) {
    // console.log(name);
  }
  return +transcation_classification_enum.find(item => item.value === name)?.key;
}


module.exports = BillController;
